//
//  NSMenuExtension.swift
//  JKTools
//
//  Created by 姜奎 on 2024/4/23.
//

import Cocoa

extension NSMenu {
    
    class func menu() -> NSMenu {
        let menu = NSMenu.init()
        menu.autoenablesItems = false
        return menu
    }

    @discardableResult
    func addItem(title string: String, keyEquivalent charCode: String = "", action close:(()->Void)? = nil) -> NSMenu {
        if !self.items.isEmpty {
            self.addItem(.separator())
        }

        let item = NSMenuItem.menu(title: string, keyEquivalent: charCode, action: close)
        addItem(item)
        return self
    }
}

extension NSMenuItem {
    
    public static func menu(title string: String, keyEquivalent charCode: String, action close:(()->Void)? = nil) -> NSMenuItem {
        let item = NSMenuItem(title: string, action: #selector(Self.targetAction), keyEquivalent: charCode)
        item.target = item
        item.actionClose = close
        return item
    }
    
    private static var actionCloseAssociatedKey: Int = 0
    
    @objc func targetAction() {
        guard let actionClose = actionClose else { return }
        actionClose()
    }
    
    private var actionClose: (()-> Void)? {
        get {
            return objc_getAssociatedObject(self, &Self.actionCloseAssociatedKey) as? (()->Void)
        }
        set {
            objc_setAssociatedObject(self, &Self.actionCloseAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}
